package com.gaoqi.mq.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RabbitMQ {
    private static ConnectionFactory connectionFactory;

    static {
        //静态初始化mq连接工厂对象
        connectionFactory = new ConnectionFactory();
        //设置连接mq主机
        connectionFactory.setHost("192.168.136.130");
        //设置端口号
        connectionFactory.setPort(5672);
        //设置连接虚拟主机名
        connectionFactory.setVirtualHost("/ems");
        //设置连接访问虚拟主机的用户名和密码
        connectionFactory.setUsername("ems");
        connectionFactory.setPassword("123");
    }

    //
    public static Connection getRabbitConnection() {

        try {
            //返回mq 连接对象
            return connectionFactory.newConnection();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //关闭通道和mq连接
    public static void closeChannelAndConnection(Channel channel, Connection conn) {
        try {
            if (channel != null) {
                channel.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
